<template>
  <base-container>
    <!-- 搜索栏 -->
    <avue-table-search
      :option="searchOption"
      v-model="searchParams"
      @search-change="loadTableSearch"
      @search-reset="loadTableSearchReset"
    />
    <!-- 卡片容器 -->
    <base-table-card>
      <template #header-right>
        <el-button type="primary" @click="handleOpenAddDialog">新增应用</el-button>
      </template>
      <avue-crud
        ref="avueCrudRef"
        :option="tableOption"
        :data="tableData"
        v-model="formData"
        :page="page"
        :table-loading="tableLoading"
        :before-open="handleBeforeOpen"
        @refresh-change="loadGetTableData"
        @current-change="loadTablePageChange"
        @size-change="loadTablePageSizeChange"
        @row-save="loadAdd"
        @row-update="loadEdit"
      >
        <!-- 图片logo上传 -->
        <template #logoUrl-form>
          <el-upload
            class="avatar-uploader"
            action="#"
            :limit="1"
            :auto-upload="false"
            :show-file-list="false"
            :on-change="uploadApplicationImage"
            accept=".png,.jpeg,.jpg"
          >
            <el-image
              v-if="formData.logoUrl"
              :src="formData.logoUrl"
              fit="contain"
              style="width: 100px; height: 100px"
            />
            <base-icon v-else name="iconfont-general gen-zhaoxiangji" :size="44" color="var(--bd7)" />
          </el-upload>
        </template>
        <!-- 添加参数 -->
        <template #configParams-form>
          <el-button class="btn" color="#5947F1" plain @click="addConfigParams">添加参数</el-button>
          <div class="configParams-content">
            <el-row class="configParams-row" v-for="(item, index) in formData.configParams" :key="index">
              <el-col :span="10">
                <el-input clearable maxlength="100" v-model="item.key" placeholder="参数名称" />
              </el-col>
              <el-col :span="1" :style="{ textAlign: 'center' }">:</el-col>
              <el-col :span="10">
                <el-input clearable maxlength="100" v-model="item.value" placeholder="参数值" />
              </el-col>
              <el-col :span="3" @click="removeConfigParams(index)">
                <base-icon
                  :style="{ textAlign: 'center', color: '#B3B1C6' }"
                  name="iconfont-general gen-cuowu"
                  :size="18"
                />
              </el-col>
            </el-row>
          </div>
        </template>
        <template #menu="{ row }">
          <el-button type="primary" text @click="handleEdit(row)">编辑</el-button>
        </template>
      </avue-crud>
    </base-table-card>
  </base-container>
</template>

<script setup>
  import useCrudHook from "avue-table/useCrudHook";
  import Option from "@/crudOption/application/config";
  import { ElMessageBox } from "element-plus";

  onMounted(async () => {
    // 获取应用类别字典
    await loadApplicableCategoryIdDict();
    // 获取应用类型字典
    await loadApplicableTypeListDict();
    // 获取表格数据
    loadGetTableData();
  });

  // 文件上传
  const uploadApplicationImage = file => {
    const form = new FormData();
    form.append("file", file.raw);
    Api.common.fileUpload(form).then(res => {
      formData.value.logoUrl = res.data;
      // nextTick(() => {
      //   uploadRef.value.clearFiles();
      // });
    });
  };

  // avue-crud 组件实例
  const avueCrudRef = ref({});

  // 增删改查 hook
  let {
    data: tableData,
    loading: tableLoading,
    page: page,
    search: searchParams,
    form: formData,
    get: loadGetTableData,
    add: loadAdd,
    edit: loadEdit,
    pageNumChange: loadTablePageChange,
    pageSizeChange: loadTablePageSizeChange,
    searchReset: loadTableSearchReset,
    searchChange: loadTableSearch,
  } = useCrudHook({
    get: Api.application.serviceProviderList,
    add: Api.application.serviceProviderAdd,
    edit: Api.application.serviceProviderUpdate,
    dataRes: "data.records",
    getParamsFormat: params => {
      // 新增时间
      console.log("🚀 ~ params:", params);
      if (params.createTime && params.createTime.length === 2) {
        params.createBeginTime = `${params.createTime[0]}`;
        params.createEndTime = `${params.createTime[1]}`;
        delete params.createTime;
      }
      // 编辑时间
      if (params.updateTime && params.updateTime.length === 2) {
        params.updateBeginTime = `${params.updateTime[0]}`;
        params.updateEndTime = `${params.updateTime[1]}`;
        delete params.updateTime;
      }
      // 返回查询参数
      return params;
    },
    addParamsFormat: row => ({
      ...row,
      configParams: (Array.isArray(row.configParams) ? row.configParams : []).reduce((obj, item) => {
        obj[item.key] = item.value;
        return obj;
      }, {}),
    }),
    editParamsFormat: row => ({
      ...row,
      configParams: (Array.isArray(row.configParams) ? row.configParams : []).reduce((obj, item) => {
        obj[item.key] = item.value;
        return obj;
      }, {}),
    }),
  });

  // 获取 搜索配置 和 表格配置
  const { searchOption, tableOption } = Option(formData);

  // 1) 获取「应用类别」字段配置
  const getApplicableApiCategoryId = () => tableOption.value?.group?.[0]?.column?.apiCategoryId;
  const getApplicableListApiCategoryId = () => tableOption.value?.column?.apiCategoryId;
  const getApplicableSearchApiCategoryId = () => searchOption.value?.formConfig?.apiCategoryId;
  // 2) 拉取字典，并写入配置（根级默认显示全部）
  async function loadApplicableCategoryIdDict() {
    const res = await Api.application.primaryList();
    const col = getApplicableApiCategoryId();
    const colList = getApplicableListApiCategoryId();
    const colSearch = getApplicableSearchApiCategoryId();
    if (col)
      col.dicData = (res?.data || []).map(i => ({
        label: i.name,
        value: i.id,
      }));
    if (colList)
      colList.dicData = (res?.data || []).map(i => ({
        label: i.name,
        value: i.id,
      }));
    if (colSearch)
      colSearch.dicData = (res?.data || []).map(i => ({
        label: i.name,
        value: i.id,
      }));
    colSearch.dicData.unshift({ label: "全部", value: "" });
  }
  // 1) 获取「应用类型」字段配置
  const getApplicableType = () => tableOption.value?.group?.[0]?.column?.type;
  const getApplicableListType = () => tableOption.value?.column?.type;
  const getApplicableSearchType = () => searchOption.value?.formConfig?.type;
  // 2) 拉取字典，并写入配置（根级默认显示全部）
  async function loadApplicableTypeListDict() {
    const res = await Api.application.serviceProviderTypeList();
    const col = getApplicableType();
    const colList = getApplicableListType();
    const colSearch = getApplicableSearchType();
    if (col)
      col.dicData = (res?.data || []).map(i => ({
        label: i.description,
        value: i.type,
      }));
    if (colList)
      colList.dicData = (res?.data || []).map(i => ({
        label: i.description,
        value: i.type,
      }));
    if (colSearch)
      colSearch.dicData = (res?.data || []).map(i => ({
        label: i.description,
        value: i.type,
      }));
    colSearch.dicData.unshift({ label: "全部", value: "" });
  }
  // 弹窗打开前
  const handleBeforeOpen = done => {
    // 获取应用类别字典
    loadApplicableCategoryIdDict();
    // 获取应用类型字典
    loadApplicableTypeListDict();
    nextTick(done);
  };

  // 打开新增弹窗
  const handleOpenAddDialog = () => {
    formData.value = { ...formData.value };
    avueCrudRef.value.rowAdd();
  };

  // 将后端返回的处理显示
  function mapCategoriesToPaths(configParams) {
    return Object.keys(configParams).map(key => ({
      key: key,
      value: configParams[key],
    }));
  }

  // 编辑时回显数据
  function handleEdit(row) {
    const paths = mapCategoriesToPaths(row?.configParams);
    // console.log("🚀 ~ handleEdit ~ paths:", paths);
    row.configParams = paths;
    avueCrudRef.value?.rowEdit({
      ...row,
    });
  }

  // 添加参数
  function addConfigParams() {
    formData.value.configParams.push({
      key: "",
      value: "",
    });
  }
  // 删除参数
  function removeConfigParams(index) {
    ElMessageBox.confirm("确定要删除吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }).then(() => {
      formData.value.configParams.splice(index, 1);
    });
  }
</script>

<style lang="scss" scoped>
  .avatar-uploader {
    width: 100px;
    height: 100px;
    border: 1px dashed #ccc;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 30px;
    .upload-btn {
      width: 100px;
      height: 100px;
      display: flex;
      align-items: center;
      justify-content: center;
      .class-img {
        width: 100%;
        height: 100%;
      }
    }
  }
  .btn {
    margin-bottom: 12px;
    background-color: #fff;
  }
  .btn:hover {
    color: #5947f1;
  }
  .configParams-row {
    margin-bottom: 12px;
  }
  .el-col-3 {
    text-align: center;
    line-height: 2;
  }
</style>
